<?php

namespace app\api\controller;


use addons\epay\library\Service;
use app\admin\model\jeek\shop\SkuGoods;
use app\admin\model\jeek\shop\SkuProduct;
use app\common\controller\Api;
use app\common\model\ChatMessages;
use app\common\model\ChatSessions;
use app\common\model\Couponlog;
use app\common\model\Order;
use app\common\model\OrderEvaluate;
use think\Db;
use think\Log;
use think\Request;

/**
 * 咨询
 */
class SeekOrder extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->goodsModel = new \app\admin\model\jeek\shop\SkuGoods;
        $this->specModel = new \app\admin\model\jeek\shop\SkuSpec;
        $this->itemModel = new \app\admin\model\jeek\shop\SkuItem;
        $this->productModel = new \app\admin\model\jeek\shop\SkuProduct;
    }

    /**
     * Account:咨询聊天页面数据
     * User: Ixiangang
     * Date: 2025/2/7
     * Time: 16:40
     */
    public function index($goods_id)
    {
        $user_id = $this->auth->id;
        # 查询咨询师信息 info 查询基础信息
        $goods = $this->goodsModel->getInfo($goods_id, $user_id, 'info');
        # 页面图文提醒
        $chat_con = config('site.chat_con');
        $orderEvaluateCount = OrderEvaluate::where('goods_id', $goods->id)->count();
        $this->success("OK", compact('goods', 'chat_con', 'orderEvaluateCount'));
    }


    /**
     * Account:发送消息记录
     * User: Ixiangang
     * Date: 2025/2/7
     * Time: 17:40
     */
    public function sendSave(Request $request)
    {
        $user_id = $this->auth->id;
        $sender_type = $request->post('sender_type'); //user=用户，consultant=咨询师
        $side_id = $request->post('side_id'); //对方ID
        $message_type = $request->post('message_type'); //消息类型：text=图文,audio=音频,video=视频
        $content = $request->post('content'); //内容
        if (!$content) $this->error("内容不能为空");
        # 获取 用户ID 咨询师ID
        $userGoodsId = (new ChatMessages())->getUserGoodsId($user_id, $side_id, $sender_type);
        # 查询 会话是否存在
        $chatSessionsInfo = ChatSessions::where(['user_id' => $userGoodsId['user_id'], 'goods_id' => $userGoodsId['goods_id'], 'status' => "active", 'message_type' => $message_type])->find();
        if (empty($chatSessionsInfo)) {
            # 存入消息会话表
            $order_id = 0;
            $sessions_id = ChatSessions::insertGetId([
                'user_id' => $userGoodsId['user_id'],
                'goods_id' => $userGoodsId['goods_id'],
                'message_type' => $message_type,
                'order_id' => $order_id,
                'status' => "active",
                'start_time' => time(),
                'createtime' => time(),
            ]);
        } #查询已有的会话
        else {
            $sessions_id = $chatSessionsInfo->id;
            $order_id = $chatSessionsInfo->order_id;
        }
        if (!$sessions_id) $this->error("会话存储失败");
        # 用户发消息做限制
        if ($sender_type == 'user') {
            # 免费图文聊天是否是使用完成 使用完成关闭会话
            (new ChatMessages())->userIf($userGoodsId['user_id'], $userGoodsId['goods_id'], $sessions_id, $message_type);
        }
        # 咨询师给用户发消息
        if ($sender_type == 'consultant') {
            (new ChatMessages())->consultantIf($userGoodsId['user_id'], $userGoodsId['goods_id'], $sessions_id, $order_id, $message_type);
        }
        # 存入聊天记录
        $data = [
            'user_id' => $userGoodsId['user_id'],
            'goods_id' => $userGoodsId['goods_id'],
            'sessions_id' => $sessions_id,
            'content' => $content,
            'sender_type' => $sender_type,
            'message_type' => $message_type,
            'is_read' => 0,
            'order_id' => $order_id,
            'created_at' => date("Y-m-d H:i:s", time()),
            'createtime' => time(),
        ];
        $rs = ChatMessages::insertGetId($data);
        if (!$rs) $this->error("消息记录存储失败");
        $this->success("发送成功", $rs);
    }

    /**
     * Account:用户创建订单
     * User: Ixiangang
     * Date: 2025/2/8
     * Time: 14:35
     */
    public function createOrder(Request $request)
    {
        $user_id = $this->auth->id;
        $vip = $this->auth->getUser()->vip;  //当前下单用户是否是vip
        # 订单编号
        $order_sn = 'SN_' . date('YmdHis') . rand(1111, 9999);
        $goods_id = $request->post('goods_id'); //咨询师ID
        $order_type = $request->post('order_type'); //服务类型:text=图文,audio=音频,video=视频
        $duration_name = $request->post('duration_name'); //购买时长
        $coupon_log_id = $request->post('coupon_log_id', 0); //优惠卷ID
        $price = $request->post('price'); //服务价格
        $discount_price = $request->post('discount_price', 0); //vip折扣价
        $pay_price_post = $request->post('pay_price'); //前段传实际支付价格
        # 查询是否有未完成订单
        $orderIs = Order::where(['user_id' => $user_id, 'goods_id' => $goods_id, 'order_type' => $order_type, 'status' => ['in', ['pending', 'active']]])->find();
        if (!empty($orderIs)) {
            $this->error("针对于咨询师订单未完成，请先使用完成");
        }
        $coupon_price = 0;
        if ($coupon_log_id != 0) {
            $couponlog = Couponlog::where('id', $coupon_log_id)->find();
            if (empty($couponlog)) $this->error("优惠卷信息不存在");
            $coupon_price = $couponlog->coupon_price; //优惠金额
        }
        # 用户下单 是获取vip 折扣价 还是原价
        $actual_price = $vip == 1 ? $discount_price : $price;  //没有优惠价格

        $pay_price = bcsub($actual_price, $coupon_price, 2); //实际支付价格
        if ($pay_price_post != $pay_price) $this->error("前段实际金额计算错误");

        # 查询合伙人是否存在
        $userpid = \app\common\model\User::where('id', \app\common\model\User::where('id', $user_id)->value('pid'))->find();
        $pid = !empty($userpid) ? $userpid->id : 0;
        # 获取分钟数值
        preg_match('/\d+/', $duration_name, $matches);
        $duration = $matches[0] ?? '';
        $data = [
            'order_sn' => $order_sn,
            'user_id' => $user_id,
            'goods_id' => $goods_id,
            'order_type' => $order_type,
            'duration_name' => $duration_name,
            'duration' => $duration,
            'coupon_log_id' => $coupon_log_id,
            'coupon_price' => $coupon_price,
            'price' => $price,
            'discount_price' => $discount_price,
            'user_vip' => $vip,
            'pay_price' => $pay_price,
            'user_pid' => $pid,
            'createtime' => time(),
            'status' => 'paytreat', //待支付
        ];
        $order_id = Order::insertGetId($data);
        if (!$order_id) $this->error("创建失败");
        # 分佣
        (new Order())->getCompare($order_id);
        $this->success("创建成功", ['order_id' => $order_id]);
    }


    /**
     * Account:订单支付
     * User: Ixiangang
     * Date: 2025/2/10
     * Time: 08:35
     */
    public function pay_order()
    {
        $order_id = $this->request->post('order_id');
        $pay_type = $this->request->post('pay_type'); //支付类型:wechat=微信,alipay=支付宝
        if (!in_array($pay_type, ['wechat', 'alipay'])) $this->error("支付类型错误");
        if ($pay_type == "wechat") {
            if (!$this->auth->app_openid) $this->error('请先绑定微信');
        }
        $order = Order::get($order_id);
        if (empty($order)) $this->error("订单信息不存在");
        if ($order->status != 'paytreat') $this->error("订单状态错误");
        $order_sn = 'SN_' . date('YmdHis') . rand(1111, 9999);
        $order->order_sn = $order_sn;
        $order->save();
        $params = [
            'amount' => $order['pay_price'],
            'orderid' => $order_sn,
            'type' => $pay_type,
            'title' => "用户下单",
            'notifyurl' => $this->request->root(true) . '/api/pay/notify/paytype/' . $pay_type,
            'returnurl' => $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $pay_type . '/out_trade_no/' . $order['order_sn'],
            'method' => 'app',
            'openid' => $this->auth->app_openid,
        ];
        $pay = Service::submitOrder($params);
        $this->success('支付成功', compact('pay', 'pay_type'));
    }


    /**
     * Account:用户返回（计算订单剩余多少分钟）注：针对于图文聊天
     * User: Ixiangang
     * Date: 2025/2/12
     * Time: 14:03
     * todo接口暂无使用
     */
    public function userReturnText($goods_id, $meter_is)
    {
        //计时类型：0=停止计时，1=开始计时
        if (!in_array($meter_is, ['0', '1'])) {
            $this->error("计时类型错误！");
        }
        $user_id = $this->auth->id;
        # 查询会话
        $chat = ChatSessions::where(['user_id' => $user_id, 'goods_id' => $goods_id, 'status' => "active", "message_type" => 'text'])->find();
        if (empty($chat)) $this->error("查询不到活动会话");
        if ($chat->order_id == 0) {
            $this->error("不需要处理");
        }
        # 查询订单
        $order = Order::where('id', $chat->order_id)->find();
        if ($order->status != "active") $this->error("订单未正式开启会话");
        # 进入聊天页面
        if ($meter_is == 1) {
            $order->meter_is = 1; //开始计时
            $order->start_time = time();
            $order->end_time = $end_time = time() + $order->remaining_second;
            $timeDifference = $end_time - time();
            $remaining_minutes1 = ceil($timeDifference / 60);  //剩余多少分钟
            $order->remaining_minutes = $remaining_minutes1;
            $order->remaining_second = $timeDifference;
            $order->save();
            if ($order->end_time < time()) {
                # 关闭会话更改订单状态
                $order->orderEndChatSessions($order->id);
            }
            $this->success("OK");
        } else {
            if ($order->meter_is != 1) $this->error("未在聊天页面");
            # 计算剩余时间
            $timeDifference = $order->end_time - time();
            $remaining_minutes2 = ceil($timeDifference / 60);  //剩余多少分钟
            # 时间到直接关闭会话 结束订单
            if ($timeDifference < 0) {
                (new Order())->orderEndChatSessions($order->id);
            }
            $order->remaining_minutes = $remaining_minutes2;
            $order->remaining_second = $timeDifference;
            # 重新计算开始结束时间
            $order->start_time = time();
            $order->end_time = time() + $timeDifference;
            $order->meter_is = 0; //停止计时
            $order->save();
        }
        $this->success("OK");
    }



    /**
     * Account:防止用户一直停留聊天页面-【不进入计时】在次发消息时 开始计时 注：针对于图文聊天
     * User: Ixiangang
     * Date: 2025/2/17
     * Time: 17:44
     * todo接口暂无使用
     */
    public function userReturnTextCheck($goods_id)
    {
        $chat = ChatSessions::where(['user_id' => $this->auth->id, 'goods_id' => $goods_id, 'status' => "active", "message_type" => 'text'])->find();
        if (empty($chat)) $this->error("查询不到活动会话");
        if ($chat->order_id == 0) {
            $this->error("不需要处理");
        }
        $order = Order::where('id', $chat->order_id)->find();
        if ($order->status == "active") {
            // 咨询师回复消息 计算时间忽略不计，用户回消息开始计时
//            $order->start_time = time();
//            $order->end_time = $end_time = time() + $order->duration * 60;
//            // 计算相差 秒 分钟
//            $timeDifference = $end_time - time();
//            $remaining_minutes = ceil($timeDifference / 60);  //剩余多少分钟
//            $order->remaining_minutes = $remaining_minutes; //分钟
//            $order->remaining_second = $timeDifference; //秒
            # 启动计时
            $order->meter_is = 1;
            $order->save();
            $this->success();
        }
        $this->error("不需要处理");
    }


    /**
     * Account:用户端请求查询订单信息
     * User: Ixiangang
     * Date: 2025/3/7
     * Time: 15:41
     */
    public function userOrderText($goods_id){
        $user_id = $this->auth->id;
        # 查询会话
        $chat = ChatSessions::where(['user_id' => $user_id, 'goods_id' => $goods_id, 'status' => "active", "message_type" => 'text'])->find();
        if (empty($chat)) $this->error("查询不到活动会话");
        if ($chat->order_id == 0) {
            $this->error("不需要处理");
        }
        # 查询订单
        $order = Order::where('id', $chat->order_id)->find();
        if ($order->status != "active") $this->error("订单未正式开启会话");
        $this->success("OK",[
            'order_id' => $order->id,
            'start_time' => $order->start_time,
            'end_time' => $order->end_time,
        ]);
    }




    /**
     * Account:处理咨询师打音视频电话与 用户挂断电话操作  注：咨询师 用户端都使用
     * User: Ixiangang
     * Date: 2025/2/14
     * Time: 11:08
     */
    public function userGoodsReturnaudioVideo()
    {
        $message_type = $this->request->post('message_type'); //audio=音频,video=视频
        if (!in_array($message_type, ['audio', 'video'])) $this->error("参数错误");
        $meter_is = $this->request->post('meter_is', 0); //0=挂断 1=已接通
        $userHangsUp = $this->request->post('user_hangs_up', 0); //1=用户挂断
        if ($userHangsUp == 1) {
            $user_id = $this->auth->id;
            $goods_id = $this->request->post('goods_id');
        } else {
            # 查询咨询师ID
            $goods_id = SkuGoods::where('user_id', $this->auth->id)->value('id');
            $user_id = $this->request->post('user_id');
        }
        # 查询会话
        $chat = ChatSessions::where(['user_id' => $user_id, 'goods_id' => $goods_id, 'status' => "active", "message_type" => $message_type])->find();
        if (empty($chat)) $this->error("查询不到活动会话");
        # 查询订单
        $order = Order::where('id', $chat->order_id)->find();
        if (empty($order)) {
            $this->error("订单信息不存在");
        }
        # 接通
        if ($meter_is == 1) {
            # 第一次接通
            if ($order->status == "pending") {
                # 第一次接通后更新订单信息
                $order->status = "active";
                $order->start_time = time();
                $end_time = time() + $order->duration * 60;
                $timeDifference = $end_time - time();
                $remaining_minutes = ceil($timeDifference / 60);  //剩余多少分钟
                $order->remaining_minutes = $remaining_minutes; //分钟
                $order->remaining_second = $timeDifference; //秒
                $order->end_time = $end_time;
            }
            # 后续音频视频接通后执行程序
            if ($order->status == "active") {
                $order->start_time = time();
                $order->end_time = $end_time = time() + $order->remaining_second;
                $timeDifference = $end_time - time();
                $remaining_minutes = ceil($timeDifference / 60);  //剩余多少分钟
                $order->remaining_minutes = $remaining_minutes; //秒
                $order->remaining_second = $timeDifference; //分钟
            }
            $order->meter_is = 1;
            $order->save();
            $this->success("接通后请求成功", ['end_time_second' => $order->remaining_second]);
        }
        # 挂断
        if ($meter_is == 0) {
            # 计算剩余时间
            $timeDifference = $order->end_time - time();
            $remaining_minutes = ceil($timeDifference / 60);  //剩余多少分钟
            Log::log("打印11111继续倒计时了前段");
            # 时间到直接关闭会话 结束订单
            if ($remaining_minutes <= 0) {
                Log::log("打印userGoodsReturnaudioVideo：方法进入");
                (new Order())->orderEndChatSessions($order->id);
            }
            # 重新计算开始结束时间
            $order->start_time = time();
            $order->end_time = time() + $timeDifference;
            $order->meter_is = 0; //停止计时
            # 计算出剩余时间分钟，秒
            $order->remaining_minutes = $remaining_minutes; //分钟
            $order->remaining_second = $timeDifference; //秒
            $order->save();
            $this->success("挂断请求成功");
        }
    }


    /**
     * Account:检测用户是否购买音频或者视频订单
     * User: Ixiangang
     * Date: 2025/2/25
     * Time: 17:24
     */
    public function userCheck()
    {
        $user_id = $this->auth->id;
        $message_type = $this->request->post('message_type'); //audio=音频,video=视频
        if (!in_array($message_type, ['audio', 'video'])) $this->error("参数错误");
        $goods_id = $this->request->post('goods_id');
        # 查询会话
        $chat = ChatSessions::where(['user_id' => $user_id, 'goods_id' => $goods_id, 'status' => "active", "message_type" => $message_type])->find();
        if (empty($chat)) {
            $code = 0;
        } else {
            # 查询订单
            $order = Order::where('id', $chat->order_id)->find();
        }
        $code = !empty($order) ? 1 : 0;
        $msg = $code == 0 ? '请先下单' : "您已下单,请与咨询师预约好时间！注：有免费图文聊天次数";
        $this->success("OK", ['check' => $code, 'msg' => $msg]);
    }


    /**
     * Account:咨询师点击音频视频检测  用户是否下单
     * User: Ixiangang
     * Date: 2025/2/26
     * Time: 09:06
     */
    public function goodsCheck()
    {
        $message_type = $this->request->post('message_type'); //audio=音频,video=视频
        if (!in_array($message_type, ['audio', 'video'])) $this->error("参数错误");
        $goods_id = SkuGoods::where('user_id', $this->auth->id)->value('id');
        $user_id = $this->request->post('user_id');
        # 查询会话
        $chat = ChatSessions::where(['user_id' => $user_id, 'goods_id' => $goods_id, 'status' => "active", "message_type" => $message_type])->find();
        if (empty($chat)) {
            $code = 0;
        } else {
            # 查询订单
            $order = Order::where('id', $chat->order_id)->find();
        }
        $code = !empty($order) ? 1 : 0;
        $msg = $code == 0 ? '请先图文联系,用户下单购买' : "已购买可以打电话";
        $this->success("OK", ['check' => $code, 'msg' => $msg]);
    }


    /**
     * Account:用户端我的订单
     * User: Ixiangang
     * Date: 2025/2/12
     * Time: 10:23
     */
    public function orderUserList()
    {
        $user_id = $this->auth->id;
        $order = new Order();
        $status = $this->request->get('status', '');
        $list = $order->getOrderList(['user_id' => $user_id, 'status' => $status]);
        $this->success("OK", $list);
    }


    /**
     * Account:用户端订单详情
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 09:04
     */
    public function orderUserDetail(Request $request)
    {
        $order_id = $request->get('order_id');
        $order = (new Order())->getOrderDetail($order_id);
        if (!$order) {
            $this->error("订单信息查询不到");
        }
        $this->success("OK", $order);
    }

    /**
     * Account:用户取消订单退款
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 09:55
     */
    public function orderCancelRefund($order_id)
    {
        $rs = (new Order())->orderRefund($order_id);
        if (!$rs) $this->error('退款失败');
        $this->success("退款成功");
    }

    /**
     * Account:用户订单评价
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 11:07
     */
    public function orderEvaluateAdd($order_id, $content)
    {
        if (!$order_id || !$content) $this->error("参数错误");
        $order = Order::get(['id' => $order_id, 'user_id' => $this->auth->id]);
        if (empty($order)) $this->error("未查询订单");
        # 查询是是否评价过该订单
        $orderEvaluate = OrderEvaluate::where(['order_id' => $order_id])->find();
        if (!empty($orderEvaluate)) {
            $this->error("您已评价过订单，请勿重复评价");
        }
        $data = [
            'user_id' => $order->user_id,
            'goods_id' => $order->goods_id,
            'order_id' => $order->id,
            'content' => $content,
            'createtime' => time(),
        ];
        $row = OrderEvaluate::create($data);
        if (!$row) $this->error("评价失败");
        $order->status = "evaluated";
        $order->save();
        $this->success("评价成功");
    }




    /**------------------------咨询师端----------------------------*/

    /**
     * Account:咨询师我的订单
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 16:06
     */
    public function orderGoodsList()
    {
        $goods_id = $this->goodsModel->where('user_id', $this->auth->id)->value('id');
        $order = new Order();
        $status = $this->request->get('status', '');
        $list = $order->getOrderList(['goods_id' => $goods_id, 'status' => $status]);
        $this->success("OK", $list);
    }

    /**
     * Account:咨询师订单详情
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 16:17
     */
    public function orderGoodsDetail(Request $request)
    {
        $order_id = $request->get('order_id');
        $order = (new Order())->getOrderDetail($order_id);
        if (!$order) {
            $this->error("订单信息查询不到");
        }
        $this->success("OK", $order);
    }


}